package com.learn.utils;


import com.learn.dto.base.BaselineReqInfo;

import java.util.Optional;

/**
 * 线程上下文工具类
 * 这里主要用来保存用户信息
 *
 * @author zhouhaofeng
 * @version 2022/10/20 0020
 * @see [相关类/方法]
 * @since [cloud-phone-baseline]
 */
public class ThreadLocalUtil
{
	private ThreadLocalUtil ()
	{

	}

	private final ThreadLocal<BaselineReqInfo> reqInfoThreadLocal = new ThreadLocal<> ();

	private static final ThreadLocalUtil instance = new ThreadLocalUtil ();

	public static ThreadLocalUtil getInstance ()
	{
		return instance;
	}

	/**
	 * 将接口请求信息对象绑定到当前线程中，键为apiReqInfoThreadLocal对象，值为ApiReqInfo对象
	 *
	 * @param baselineReqInfo 接口请求信息对象
	 */
	public void bind (BaselineReqInfo baselineReqInfo)
	{
		reqInfoThreadLocal.set (baselineReqInfo);
	}

	/**
	 * 移除当前线程的接口请求信息，在请求结束调用，避免线程池复用导致接口请求信息不一致问题
	 */
	public void removeReqInfo ()
	{
		reqInfoThreadLocal.remove ();
	}

	/**
	 * 获取当前接口请求信息
	 */
	public BaselineReqInfo getReqInfo ()
	{
		return Optional.ofNullable (reqInfoThreadLocal.get ()).orElseGet (BaselineReqInfo::new);
	}
}
